<template>
  <div class="listbody">
    <div class="postionform">
      <el-form :inline="true" :model="queryParams" >
        <el-form-item label="">
          <el-input v-model="queryParams.keyword" size="small" placeholder="活动关键字" clearable @keyup.native.enter="handleQuery"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="handleQuery">查询</el-button>
        </el-form-item>
      </el-form>
    </div>
    <div v-if="!tableData.length" class="flexcenter c_999 mt_20">暂无数据</div>
    <div
      v-for="(item, index) in tableData"
      :key="index"
      class="flexrowbetween listbox"
    >
      <div class="flex itemleft">
        <div class="mr_30">
          <img :src="item.img" class="fmimg" alt="" />
        </div>
        <div>
          <div class="mb_15">
            <span class="pr_10 f-14">{{ item.name }}</span>
            <template v-if="item.status == 1">
              <el-tag
                v-if="new Date(item.draw_startime).getTime() > Date.now()"
                type="warning"
                class="tag_success"
                >未开始</el-tag
              >
              <el-tag v-else type="success" class="tag_success">进行中</el-tag>
            </template>
            <!-- <el-tag
              v-if="item.status == 1"
              type="success"
              size="mini"
              class="tag_success"
              >进行中</el-tag
            > -->
            <el-tag
              v-if="item.status == 0"
              type="info"
              size="mini"
              class="tag_success"
              >未发布</el-tag
            >
            <el-tag
              v-if="item.status == 4"
              type="danger"
              size="mini"
              class="tag_success"
              >已结束</el-tag
            >
          </div>
          <div class="mb_15 c_b3 f-14">
            {{ item.draw_startime }} 至 {{ item.draw_endtime }}
          </div>
          <div class="f-14 c_b3">
            <span class="pr_15"
              >参与次数：<span class="c_primary">{{
                item.count_list.draw
              }}</span></span
            >
            <span class="pr_15"
              >中奖数：<span class="c_primary">{{
                item.count_list.draw_win
              }}</span></span
            >
            <span class="pr_15"
              >访问量：<span class="c_primary">{{
                item.count_list.record
              }}</span></span
            >
          </div>
        </div>
      </div>
      <div class="itemright">
        <div class="mb_32" v-if="item.status == 0">
          <svg-icon
            icon-class="refer"
            class-name="f-24 commhover"
            @click="handleShare(item)"
          />
        </div>
        <div>
          <!-- v-if="item.status !== 4" -->
          <span
            class="c_primary mr_20 f-13 commhover"
            @click="handleEdit(item)"
            >编辑</span
          >
          <span class="c_primary mr_20 f-13 commhover" @click="handleCopy(item)"
            >复制</span
          >
          <span
            class="c_BE0000 mr_20 f-13 commhover"
            v-if="item.status == 1"
            @click="handleClose(item)"
            >结束</span
          >
          <span v-if="item.status !== 1"
            class="c_BE0000 mr_20 f-13 commhover"
            @click="handleDelete(item)"
            >删除</span
          >
          <el-dropdown
            @command="handleCommand($event, item)"
            v-if="item.status !== 0"
          >
            <span class="el-dropdown-link c_primary f-13">
              操作<i class="el-icon-arrow-down el-icon--right"></i>
            </span>
            <el-dropdown-menu slot="dropdown">
              <el-dropdown-item command="a">中奖名单</el-dropdown-item>
              <el-dropdown-item command="b">活动数据</el-dropdown-item>
              <el-dropdown-item command="c">用户核销</el-dropdown-item>
              <!-- <el-dropdown-item command="d">公众号授权</el-dropdown-item> -->
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
    </div>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.num"
      @pagination="getList"
    />
    <el-dialog :visible.sync="open" width="720px" :before-close="closeOpen" :close-on-click-modal='false'>
      <template slot="title">
        <div class="textcenter f-20 c_000">发布活动</div>
      </template>
      <div class="flex aligncenter justifycenter p_40 pt_15">
        <div class="flexcolumn aligncenter justifycenter boximg">
          <div class="c_8c mb_16">微信扫一扫预览效果</div>
          <!-- <img :src="fabu.link1" alt="" class="imgcode mb_16" /> -->
          <div ref="h2link" id="h2link" class="imgcode mb_16"></div>
          <div class="mb_32 downbtn flexcenter commhover" @click="download(1)">下载二维码</div>
          <el-input
            placeholder="请输入内容"
            v-model="fabu.link1"
            readonly
            class="appendbg"
          >
            <template slot="append">
              <span
                class="commhover"
                v-clipboard:copy="fabu.link1"
                v-clipboard:success="clipboardSuccess"
                >复制</span
              >
            </template>
          </el-input>
        </div>
        <!-- <div class="flexcolumn aligncenter justifycenter boximg">
          <div class="c_8c mb_16" style="height: 20px"></div>
          <div class="imgcode mb_16" ref="appletlink"></div>
          <div class="mb_32 downbtn flexcenter commhover">下载小程序码</div>
          <el-input
            placeholder="请输入内容"
            v-model="fabu.link2"
            readonly
            class="appendbg"
          >
            <template slot="append">
              <span
                class="commhover"
                v-clipboard:copy="fabu.link2"
                v-clipboard:success="clipboardSuccess"
                >复制</span
              >
            </template>
          </el-input>
        </div> -->
      </div>
      <div class="flexcenter">
        <el-button type="primary" @click="handleFabu">发布活动</el-button>
      </div>
    </el-dialog>

    <el-dialog
      title="复制活动"
      center
      :visible.sync="opencopy"
      width="400px"
      :show-close="false"
      top="20vh"
    >
      <div class="flexcolumn aligncenter">
        <el-progress
          type="circle"
          :percentage="percentage"
          class="mpro"
        ></el-progress>
        <div class="mt_25 c_999">温馨提示：无法复制活动数据</div>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  taskIndex,
  btnEnding,
  btnDelete,
  btnCopy,
  btnPublish,
} from "@/api/active";
import QRCode from 'qrcodejs2'
export default {
  data() {
    return {
      tableData: [],
      queryParams: {
        page: 1,
        num: 10,
        keyword:''
      },
      total: 10,
      open: false,
      // link: "http://localhost/actmgt/active1",
      opencopy: false,
      percentage: 0,
      item: null,
      row:null,
      fabu:{
        link1:'',
        link2:''
      }
    };
  },

  props: {
    status: {
      default: "",
    },
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      this.loading = true;
      let params = { page:this.queryParams.page,num:this.queryParams.num };
      if(this.queryParams.keyword){
        params.keyword = this.queryParams.keyword
      }
      if (this.status || this.status === 0) {
        params.status = this.status;
      }
      taskIndex(params).then((response) => {
        this.tableData = response.data.list.map((item) => ({
          ...item,
          img: process.env.VUE_APP_BASE_API + "/" + item.template.url,
        }));
        this.total = response.data.count;
        this.loading = false;
        this.isrefresh = false;
      });
    },

    handleQuery(){
      this.queryParams.page = 1;
      this.getList()
    },

    download(type){
      // let qrcode = document.getElementById('h2link');
      // let img = qrcode.getElementsByTagName('img')[0];
      // console.log('img:',img)
      // // img.onload = function () {
      // let url = img.getAttribute("src");
      //   let link = document.createElement("a");
      //   console.log('imgUrl:',imgUrl)
      //   link.setAttribute("href", imgUrl);
      //   link.setAttribute("download", '二维码.png')
      //   link.click();
      // // }
      let url = document.querySelectorAll("#h2link img")[0].src;
      let a = document.createElement("a");
      let event = new MouseEvent('click');
      // 下载图名字
      a.download = '二维码.png';
      a.href = url;
      // 合成函数，执行下载
      a.dispatchEvent(event);
    },

    handleEdit(item) {
      this.$router.push({ name: "CreateTemp", query: { id: item.id } });
    },

    handleCopy(item) {
      this.opencopy = true;
      this.percentage = 0;
      let time = setInterval(() => {
        if (this.percentage == 90) {
          clearInterval(time);
          return;
        }
        this.percentage += 10;
      }, 100);
      let params = {
        id: item.id
      }
      if(localStorage.getItem('admin_id')&&localStorage.getItem('admin_id')!=='undefined'){
        params.admin_id = localStorage.getItem('admin_id')
      }
      btnCopy(params)
        .then(() => {
          clearInterval(time);
          this.percentage = 100;
          this.$message.success("复制成功");
          this.getList();
        })
        .catch(() => {
          this.$message.danger("复制失败");
          this.percentage = 0;
        });
    },

    handleClose(item) {
      this.$confirm("是否确认结束活动？确认后，该活动将无法复原", "结束活动", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          btnEnding({ id: item.id }).then(() => {
            this.$message.success("结束成功!");
            this.getList();
          });
        })
        .catch(() => {});
    },

    handleDelete(item) {
      this.$confirm("是否确认删除该活动, 删除后该活动无法复原?", "结束活动", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning",
      })
        .then(() => {
          btnDelete({ id: item.id }).then(() => {
            this.$message.success("删除成功!");
            if (this.tableData.length === 1 && this.queryParams.page !== 1) {
              this.queryParams.page --
            }
            this.getList();
          });
        })
        .catch(() => {});
    },
    handleShare(item) {
      // if(item.)
      let taskId = item.id || '0'
      this.fabu.link1 = this.h5domain + '?id='+taskId
      console.log('this.fabu.link1:', this.fabu.link1)
      this.$nextTick(()=>{
          this.$refs.h2link.innerHTML = ""
          var qrcode = new QRCode(this.$refs.h2link, {
            text: this.fabu.link1,
            width: 160,
            height: 160,
            colorDark : "#000000",
            colorLight : "#ffffff",
            correctLevel : QRCode.CorrectLevel.Q
          });
        })
      this.row = item
      this.open = true;
      // this.$confirm("是否确认发布该活动?", "发布活动", {
      //   confirmButtonText: "确定",
      //   cancelButtonText: "取消",
      //   type: "warning",
      // })
      //   .then(() => {
      //     btnPublish({ id: item.id }).then(() => {
      //       this.$message.success("发布成功!");
      //       this.getList();
      //       this.open = true;
      //     });
      //   })
      //   .catch(() => {});
    },

    handleFabu(){
      btnPublish({ id: this.row.id }).then(() => {
        this.$message.success("发布成功!");
        this.getList();
        this.open = false;
      });
    },

    closeOpen() {
      this.open = false;
    },
    clipboardSuccess() {
      this.$modal.msgSuccess("复制成功");
    },

    handleCommand(command, item) {
      console.log("command:", command);
      switch (command) {
        case "a":
          this.$router.push({ name: "WinList", query: { id: item.id } });
          break;
        case "b":
          this.$router.push({ name: "ActiveData", query: { id: item.id } });
          break;
        case "c":
          this.$router.push({ name: "Userhandle", query: { id: item.id } });
          break;
        case "d":
          this.$router.push({
            name: "Gzhauth",
            
          });
          break;
        default:
          break;
      }
    },
  },
};
</script>

<style lang="scss" scoped>
.listbody {
  height: calc(100vh - 162px);
  overflow-y: auto;
  padding-bottom: 25px;
}
.listbox {
  padding: 25px;
  border-bottom: 1px solid #d9d9d9;
  &:hover {
    background-color: #f4f7fe;
  }
}
.itemleft {
  width: calc(100% - 260px);
  padding-right: 20px;
}
.itemright {
  max-width: 260px;
  height: 94px;
  display: flex;
  flex-direction: column;
  justify-content: flex-end;
  align-items: flex-end;
}
.fmimg {
  width: 140px;
  height: 90px;
  border-radius: 8px;
}
.c_b3 {
  color: #b3b3b3;
}
.imgcode {
  width: 178px;
  height: 178px;
}
.boximg {
  // width: 320px;
  width: 420px;
}
.downbtn {
  border-radius: 4px;
  height: 32px;
  width: 100px;
  border: 1px solid #bfbfbf;
}
.mpro {
  margin: auto;
}
.postionform{
  position: absolute;
  right: 0;
  top: -52px;
  z-index: 9;
}
</style>
<style lang="scss">
.appendbg {
  .el-input-group__append {
    background-color: #4a73ff;
    color: white;
  }
}
</style>